package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// Role 角色模型
type Role struct {
	BaseModel
	Name        string `orm:"size(64);unique" json:"name"`
	Description string `orm:"size(255)" json:"description"`
	Status      int8   `orm:"default(1)" json:"status"` // 1:正常, 0:禁用
	// FranchiseId字段已经在BaseModel中定义，这里不需要重复定义
}

// TableName 设置表名
func (r *Role) TableName() string {
	return "ss_role"
}

// GetRoleById 根据ID获取角色信息
func GetRoleById(id int64) (*Role, error) {
	role := &Role{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(role)
	if err != nil {
		return nil, err
	}

	return role, nil
}

// GetRoleList 获取角色列表
func GetRoleList(page, pageSize int, filters map[string]interface{}) ([]*Role, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Role))

	// 应用过滤条件
	if franchiseId, ok := filters["franchise_id"].(int64); ok {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var roles []*Role
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&roles)

	return roles, total, err
}

// CreateRole 创建角色
func CreateRole(role *Role) (int64, error) {
	o := orm.NewOrm()
	role.BeforeInsert()
	id, err := o.Insert(role)
	return id, err
}

// UpdateRole 更新角色信息
func UpdateRole(role *Role, fields ...string) error {
	o := orm.NewOrm()
	role.BeforeUpdate()
	_, err := o.Update(role, fields...)
	return err
}

// DeleteRole 删除角色（软删除）
func DeleteRole(id int64) error {
	o := orm.NewOrm()
	role := &Role{BaseModel: BaseModel{Id: id}}
	if err := o.Read(role); err != nil {
		return err
	}

	role.IsDeleted = 1
	_, err := o.Update(role, "IsDeleted")
	return err
}

// DeleteRolePermissions 删除角色权限
func DeleteRolePermissions(roleId int64) error {
	o := orm.NewOrm()
	_, err := o.QueryTable("ss_role_permission").Filter("role_id", roleId).Delete()
	return err
}

// AddPermissions 为角色添加权限
func AddPermissionsToRole(roleId int64, permissionIds []int64) error {
	o := orm.NewOrm()
	role := &Role{BaseModel: BaseModel{Id: roleId}}
	if err := o.Read(role); err != nil {
		return err
	}

	// 清空现有权限
	_, err := o.QueryTable("ss_role_permission").Filter("role_id", roleId).Delete()
	if err != nil {
		return err
	}

	// 添加新权限
	for _, permId := range permissionIds {
		rp := &RolePermission{RoleId: roleId, PermissionId: permId}
		_, err = o.Insert(rp)
		if err != nil {
			return err
		}
	}

	return nil
}

// GetRolesByFranchiseId 获取指定加盟商的角色列表
func GetRolesByFranchiseId(franchiseId int64) ([]*Role, error) {
	o := orm.NewOrm()
	var roles []*Role
	_, err := o.QueryTable(new(Role)).Filter("franchise_id", franchiseId).Filter("is_deleted", 0).All(&roles)
	return roles, err
}
